#include <pthread.h>
#include <stdlib.h>

#include "serial.h"

#define UPS_PORT "/dev/ttyUSB0"

int ups_fd;


void analysis_data(char *buf)
{
    char *p = NULL;
    int ret = 0;
    char cmd[16] = {0};

    printf("recv data: %s\n", buf);

    p = strrchr(buf, ' ');
    if(p == NULL)
        return;
    printf("***: %s\n", p);
    p++;

    ret = strncmp(p, "1", strlen("1"));
    if(ret == 0){
        printf("*** AC POWER OFF, SHUTDOWN SYSTEM!!! ***\n");
        printf("*** AC POWER OFF, SHUTDOWN SYSTEM!!! ***\n");
        printf("*** AC POWER OFF, SHUTDOWN SYSTEM!!! ***\n");
        // sprintf(cmd, "shutdown -h now");
        sprintf(cmd, "shutdown");
        system(cmd);
    }

    printf("ret: %d\n", ret);
}

void *ups_read(void *a)
{
    char buf[128] = {0};

    while(1)
    {
        bzero(buf, sizeof(buf));
        read_data(ups_fd, buf, sizeof(buf), 200);
        analysis_data(buf);
        sleep(3);
    }
    return NULL;
}

void *ups_write(void *a)
{
    char *cmd = "Q1\r\n";

    while(1)
    {
        printf("send cmd: %s\n", cmd);
        write(ups_fd, cmd, strlen(cmd));
        sleep(3);
    }
    return NULL;
}

#if 0
int main(void)
{
    FILE *fp = NULL;
    int ret;
    pthread_t pth_ups_read;
    pthread_t pth_ups_write;
    
	/* open serial port */
	ups_fd = open_port(UPS_PORT);
	if (ups_fd < 0) {
		perror("open failed");
		close(ups_fd);
		return -1;
	}

	/* set serial port */
	ret = set_port(ups_fd, 2400, 8, 'N', 1);
	if (ret < 0) {
		perror("set_port failed");
		close(ups_fd);
		return -1;	
	}

    if(pthread_create(&pth_ups_read, NULL, ups_read, NULL) == -1){
		printf("fail to create pthread key!\n");
	}

    if(pthread_create(&pth_ups_write, NULL, ups_write, NULL) == -1){
		printf("fail to create pthread key!\n");
	}

    while(1)
    {
        printf("******************\n");
        sleep(3);
    }
    close(ups_fd);  
    return 0;
}
#else
int main(void)
{
    int ret;
    char *cmd = "Q1\r\n";
    char buf[128] = {0};

    while(1)
    {
		printf("==========================================\n");
        /* open serial port */
        ups_fd = open_port(UPS_PORT);
        if (ups_fd < 0) {
            perror("open failed");
            close(ups_fd);
            return -1;
        }

        /* set serial port */
        ret = set_port(ups_fd, 2400, 8, 'N', 1);
        if (ret < 0) {
            perror("set_port failed");
            close(ups_fd);
            return -1;	
        }
        printf("send cmd: %s\n", cmd);
        write(ups_fd, cmd, strlen(cmd));
        usleep(350*1000); //100ms

        bzero(buf, sizeof(buf));
        read_data(ups_fd, buf, sizeof(buf), 500);
        analysis_data(buf);
        sleep(120);

        close(ups_fd);
    }

    return 0;
}
#endif
